"""Various database manipulation routines"""
from loadstone import geocalc
mult=10000000.0
def excludeDeletedRecords(db):
	"""Removes items flagged as deleted from L{db}"""
	count=0
	for i,r in enumerate(db.point[:]):
		if r.isDeleted(): 
			del db.point[i-count]
			count+=1
	return count

def reduceClosePoints(db,approxDist,nameMustMatch=False):
	if nameMustMatch: #sort by lat,lon,name
		db.point.sort(key=lambda k:(k["latitude"],k["longitude"],k["name"]))
	else:
		db.point.sort(key=lambda k:(k["latitude"],k["longitude"]))
	count=0
	result=[]
	prevPoint=None
	for i,p in enumerate(db.point[:]):
		if not prevPoint or (nameMustMatch and prevPoint["name"].lower()!=p["name"].lower()): 
			prevPoint=p
			continue
		distance=geocalc.EllipsoidDistance(p["latitude"]/mult,p["longitude"]/mult,prevPoint["latitude"]/mult,prevPoint["longitude"]/mult)
		if round(distance,4)>approxDist/1000:
			prevPoint=p
		else:
			del db.point[i-count]
			count+=1
	return count